package com.ijianji.module_play_video.activity

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.dueeeke.videocontroller.StandardVideoController
import com.fenghuajueli.lib_data.entity.db.VideoInfoEntity
import com.fenghuajueli.libbasecoreui.listener.OnListClickListener
import com.fenghuajueli.libbasecoreui.viewmodel.BaseViewModelActivity
import com.fenghuajueli.module_route.PlayVideoModuleRoute
import com.ijianji.module_play_video.PlayVideoModuleInitUtils
import com.ijianji.module_play_video.R
import com.ijianji.module_play_video.adapter.VideoRecommendGridAdapter
import com.ijianji.module_play_video.adapter.VideoSelectPositionAdapter
import com.ijianji.module_play_video.databinding.ActivityVideoListPlayBinding
import com.ijianji.module_play_video.model.PlayVideoModel
import com.ijianji.module_play_video.utils.RandomUtils
import com.tik.module_function.extension.initGridVideoListAdapter
import com.tik.module_function.extension.initSelectVideoPositionAdapter

/**
 * 传入一个播单进行播放 默认播放第一集
 */
@Route(path = PlayVideoModuleRoute.ACTIVITY_VIDEO_LIST_PLAY)
class VideoListPlayActivity : BaseViewModelActivity<PlayVideoModel, ActivityVideoListPlayBinding>() {

    private var recommendGridAdapter: VideoRecommendGridAdapter? = null

    private var videoSelectPositionAdapter: VideoSelectPositionAdapter? = null

    private var controller: StandardVideoController? = null

    val PLAY_LIST_TAG: String = "PLAY_LIST_TAG"
    val RECOMMEND_LIST_TAG: String = "RECOMMEND_LIST_TAG"

    var currentVideoEntity: VideoInfoEntity? = null

    //当前正在播放的这项是否处于收藏中
    private var currentIsCollection: Boolean = false

    /**
     * 播放列表加载的集数
     */
    val PAGE_SIZE = 50

    /**
     * 推荐列表加载的长度
     */
    val RECOMMEND_PAGE_SIZE = 4

    /**
     * 当前播放视频所属的播单的id
     */
    @JvmField
    @Autowired(name = "playListId")
    var playListId: String = ""

    /**
     * 底部推荐栏的播单id
     */
    @JvmField
    @Autowired(name = "recommendPid")
    var recommendPid: String = ""


    override fun createViewModel(): PlayVideoModel {
        return PlayVideoModel()
    }

    override fun createViewBinding(): ActivityVideoListPlayBinding {
        return ActivityVideoListPlayBinding.inflate(layoutInflater)
    }

    override fun initView() {
        //view创建成功
        binding.ivBack.setOnClickListener {
            onBackPressed()
        }
        if (!TextUtils.isEmpty(playListId) && !TextUtils.isEmpty(recommendPid)) {
            initVideoView()
            initAdapter()
            setObserver()
            model.loadVideoList(this, playListId, PAGE_SIZE)
            model.loadRecommendVideoList(this, recommendPid, RECOMMEND_PAGE_SIZE)
        } else {
            showToast("必要参数为空！")
            finish()
        }
    }

    private fun setObserver() {
        model.videoUrlData.observe(this, Observer {
            setVideoInfo()
            playVideo(it)
        })
        model.videoListData.observe(this, Observer { listData ->
            if (listData.size > 0) {
                currentVideoEntity?.let { data ->
                    currentVideoEntity = listData.find { data.vid == it.vid }
                }
                if (currentVideoEntity == null) {
                    currentVideoEntity = listData[0]
                }
                val selectPosition = listData.indexOf(currentVideoEntity)
                videoSelectPositionAdapter?.selectPosition = selectPosition
                videoSelectPositionAdapter?.refreshData(listData)
                binding.rvSelectView.smoothScrollToPosition(selectPosition)
                checkHasCollection()
                updateCount()
                currentVideoEntity?.let {
                    model.getVideoRealUrl(this, it.vid)
                }
            } else {
                showToast("当前播单列表为空！")
                finish()
            }
        })
        model.recommendVideoListData.observe(this, Observer {
            recommendGridAdapter?.refreshData(it)
        })
        model.collectionStatusData.observe(this, Observer {
            currentIsCollection = it
            if (it) {
                showToast("收藏成功！")
                binding.ivCollection.setImageResource(R.mipmap.icon_collection_02)
            } else {
                showToast("取消收藏！")
                binding.ivCollection.setImageResource(R.mipmap.icon_collection_01)
            }
        })
        model.collectionCheckStatusData.observe(this, Observer {
            currentIsCollection = it
            if (it) {
                binding.ivCollection.setImageResource(R.mipmap.icon_collection_02)
            } else {
                binding.ivCollection.setImageResource(R.mipmap.icon_collection_01)
            }
        })
    }

    private fun initAdapter() {
        recommendGridAdapter = binding.videoListView.initGridVideoListAdapter(arrayListOf(), OnListClickListener { position, data ->
            //点击事件
            currentVideoEntity = data
            checkHasCollection()
            updateCount()
            model.loadVideoList(this, recommendPid, PAGE_SIZE)
        })
        videoSelectPositionAdapter = binding.rvSelectView.initSelectVideoPositionAdapter(arrayListOf(), OnListClickListener { position, data ->
            //点击事件
            currentVideoEntity = data
            checkHasCollection()
            updateCount()
            model.getVideoRealUrl(this, data.vid)
        })
    }


    private fun updateCount() {
        currentVideoEntity?.let {
            binding.tvSeeCount.text = "${RandomUtils.getSeeCount(it.vid)}人看过"
        }
    }

    private fun checkHasCollection() {
        currentVideoEntity?.let {
            model.checkVideoIsCollection(it)
        }
    }

    private fun initVideoView() {
        controller = StandardVideoController(this)
        controller?.addDefaultControlComponent("", false)
        binding.videoView.setVideoController(controller)
        binding.ivCollection.setOnClickListener {
            currentVideoEntity?.let {
                if (currentIsCollection) {
                    model.cancelCollectionVideo(it)
                } else {
                    model.collectionVideo(it)
                }
            }
        }
    }

    private fun setVideoInfo() {
        currentVideoEntity?.let {
            binding.tvVideoName.text = it.title
            model.addPlayHistory(it)
        }
    }

    private fun playVideo(videoUrl: String) {
        binding.videoView.release()
        binding.videoView.setUrl(PlayVideoModuleInitUtils.proxy.getProxyUrl(videoUrl))
        binding.videoView.start()
    }

    override fun onPause() {
        super.onPause()
        binding.videoView.pause()
    }

    override fun onResume() {
        super.onResume()
        binding.videoView.resume()
    }

    override fun onDestroy() {
        binding.videoView.release()
        super.onDestroy()
    }


    override fun onBackPressed() {
        if (!binding.videoView.onBackPressed()) {
            super.onBackPressed()
        }
    }

}